<?php

namespace Beerus\Modules\TodayNiceGoods\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\cache\brand\BlindBox;
use Biz\model\TodayNiceGoods\TodayNiceGoodsModel;
use Biz\model\wiki\Wiki;
use Biz\service\TodayNiceGoods\TodayNIceGoodsService;
use Biz\service\wiki\WikiBasic;
use Biz\tools\helper\Common;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\MessageBag;

/**
 * Description: 今日好物
 * Created by PhpStorm.
 * User: 玉坤
 * Date: 2021/5/24
 * Time: 18:17
 */
class IndexController extends Controller
{
    public const  PAGE_SIZE = 20;

    /**
     * 获取列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content): Content
    {
        Admin::script($this->auditScript());
        $params = $request->all();
        $page_size = $params['per_page'] ?? self::PAGE_SIZE;
        $params['per_page'] = $page_size;
        $where = $this->_getWhere($params);
        $list = TodayNiceGoodsModel::all($where);
        unset($where['LIMIT']);
        $count = TodayNiceGoodsModel::count($where);

        $list = TodayNIceGoodsService::formatList($list);
        $gridModel = new GridDataModel($list, $count, [
            'perPage' => $page_size,
        ]);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function ($filter) {
                    // 在这里添加字段过滤器
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('brand_id', '品牌ID')->placeholder('品牌ID');
                        $filter->equal('basic_id', 'WIKI_ID')->placeholder('WIKI_ID');
                        $filter->equal('type', '活动类型')->select(TodayNiceGoodsModel::TYPE_ARR);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('brand_name', '品牌名称')->placeholder('品牌名称');
                        $filter->equal('start_at', '上线时间')->date();
                        $filter->equal('status', '活动状态')->select(TodayNiceGoodsModel::STATUS_ARR);
                    });
                    $filter->expand();//默认展开
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'id')->sortable();
                $grid->column('brand_name', '品牌名称');
                $grid->column('brand_id', '品牌ID')->copyable();
                $grid->column('basic_id', 'WIKI_ID')->copyable();
//                $grid->column('wiki_id', '商品ID');
                $grid->column('img_url', '商品图')->display(function ($img_url) {
                    return '<a href="javascript:layer.open({type: 2,title: \'预览\',maxmin: true,area: [\'600px\', \'400px\'],content: \'' . $img_url . '\'});">
                                <img width="100px" height="100px" src="' . $img_url . '">
                            </a>';
                });
//                $grid->column('back_img_url', '背景图片')->display(function ($back_img_url) {
//                    return '<a href="javascript:layer.open({type: 2,title: \'预览\',maxmin: true,area: [\'600px\', \'400px\'],content: \'' . $back_img_url . '\'});">
//                                <img width="100px" height="100px" src="' . $back_img_url . '">
//                            </a>';
//                });
//                $grid->column('back_show_img_url', '展台图片')->display(function ($back_img_url) {
//                    return '<a href="javascript:layer.open({type: 2,title: \'预览\',maxmin: true,area: [\'600px\', \'400px\'],content: \'' . $back_img_url . '\'});">
//                                <img width="100px" height="100px" src="' . $back_img_url . '">
//                            </a>';
//                });

                $grid->column('title', '主标题')->width(200);
//                $grid->column('sec_title', '副标题');
                $grid->column('type', '活动类型')->using(
                    TodayNiceGoodsModel::TYPE_ARR
                    , '未知')->label([
                    1 => 'default',
                    2 => 'primary',
                ]);
                $grid->column('start_at', '上线时间')->sortable();
                $grid->column('status', '状态')->using(
                    TodayNiceGoodsModel::STATUS_ARR
                    , '未知')->label([
                    12 => 'success',
                    9 => 'info',
                    11 => 'warning',
                    13 => 'danger',
                ]);
                $grid->column('admin_id', '操作人');
                $grid->setActionClass(Actions::class);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableView();
                    $status = $actions->row->status;

                    if ($status != TodayNiceGoodsModel::STATUS_DELETE) {
                        $html_delete = ' <a class="fa edit-pass-data" data-state="' . TodayNiceGoodsModel::STATUS_DELETE . '" data-id="' . $actions->row->id . '" href="javascript:void(0);" style="margin-right: 5px">
                                    <span class="glyphicon" aria-hidden="true">删除</span></a>';
                        $actions->prepend($html_delete);
                    }
                    if (in_array($status, [TodayNiceGoodsModel::STATUS_END, TodayNiceGoodsModel::STATUS_DELETE])) {
                        $actions->disableEdit();
                    }
                });
            }
        );
        $tab = new Tab();
        $tab->add('找好物列表', $grid->render(), true);
        $tab->addLink('活动中排序', url('/admin/TodayNiceGoods/sortlists'), false);
        $tab->addLink('白名单', url('/admin/TodayNiceGoods/whiteusers'), false);
        $content->row($tab);

        return $content
            ->header('找好物活动')
            ->description(' ')
            ->breadcrumb(['text' => '找好物列表', 'url' => '/TodayNiceGoods/index']);
    }


    /**
     * 获取查询条件
     * @param $params
     * @return array
     */
    private function _getWhere($params): array
    {
        $id = $params['id'] ?? 0;
//        $wiki_id = $params['wiki_id'] ?? 0;
        $basic_id = $params['basic_id'] ?? 0;
        $type = $params['type'] ?? 0;
        $page = $params['page'] ?? 1;
        $page_size = $params['per_page'] ?? 20;
        $brand_name = $params['brand_name'] ?? '';
        $brand_id = $params['brand_id'] ?? '';
        $start_at = $params['start_at'] ? date('Y-m-d H:i:s', strtotime($params['start_at'])) : 0;
        $status = $params['status'] ?? "";
        if ($id) {
            $where['id'] = $id;
        }
        if ($basic_id) {
            $where['basic_id'] = $basic_id;
        }
        if ($type) {
            $where['type'] = $type;
        }
        if ($start_at) {
            $where['start_at'] = $start_at;
        }
        if ($brand_name) {
            $where['brand_name[~]'] = $brand_name . '%';
        }
        if ($brand_id) {
            $where['brand_id'] = $brand_id;
        }

        $where['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size,
        ];
        if ($status) {
            //活动中
            if ((int)$status === TodayNiceGoodsModel::STATUS_ACTING) {
                $status = TodayNiceGoodsModel::STATUS_NORMAL;
                $where['start_at[<=]'] = date('Y-m-d H:i:s');
                $where['end_at[>]'] = date('Y-m-d H:i:s');
            }
            //活动结束
            if ((int)$status === TodayNiceGoodsModel::STATUS_END) {
                $where['end_at[<]'] = date('Y-m-d H:i:s');
                $status = TodayNiceGoodsModel::STATUS_NORMAL;
            }
            //待开始
            if ((int)$status === TodayNiceGoodsModel::STATUS_WAIT) {
                $where['start_at[>]'] = date('Y-m-d H:i:s');
                $status = TodayNiceGoodsModel::STATUS_NORMAL;
            }
            $where['status'] = $status;

        }
        if (isset($params['_sort']["column"], $params['_sort']["type"])) {
            $where['ORDER'] = [
                $params['_sort']["column"] => strtoupper($params['_sort']["type"]),
            ];
        } else {
            $where['ORDER'] = [
//                'sort' => "DESC",
                'start_at' => 'DESC',
            ];
        }

        return $where;
    }

    /**
     * 更改活动状态
     * @param Request $request
     * @return JsonResponse
     */
    public function audit(Request $request): JsonResponse
    {
        try {
            $params = $request->all();

            $rule = [
                'id' => 'required|int',
                'status' => 'required|int',
            ];
            $validator_msg = Common::validatorRule($rule, $params);
            if ($validator_msg !== true) {
                throw  new \Exception($validator_msg);
            }
            $admin_id = Admin::user()->id;
            $data['id'] = $params['id'];
            $data['admin_id'] = $admin_id;
            $data['status'] = $params['status'];
            $info = TodayNiceGoodsModel::first(['id' => $params['id']]);
            if (empty($info)) {
                throw new \Exception('不存在的活动');
            }
            TodayNIceGoodsService::audit($data);
            $success = [
                'title' => '操作成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }

        return response()->json($success);

    }

    /**
     * 更改活动状态js
     * @return string
     */
    private function auditScript()
    {
        return <<<SCRIPT
        $('.edit-pass-data').unbind('click').click(function(){
            var id= $(this).data('id');
            var status=$(this).data('state');
            let url = '/admin/TodayNiceGoods/audit'
            let params = {id:id,status:status}
            swal({
                    title: "确认提交吗？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认",
                    showLoaderOnConfirm: true,
                    cancelButtonText: "取消",
                    preConfirm: function() {
                    //ajax
                        $.ajax({
                            method: 'post',
                            url: url,
                            data: params,
                            success: function (e) {
                                if (e.code == 1) {
                                swal({
                                    title: e.title,
                                    type: "warning",
                                });
                                    setTimeout(function () {
                                        $.pjax.reload('#pjax-container');
                                    }, 1000);
                                } else {
                                    toastr.error(e.title, null, {
                                        timeOut : 3000
                                    }); 
                                }
                            }
                        });
                    //ajax-end
                    }
            });
        });
       
SCRIPT;
    }

    /**
     * 编辑
     * @param $id
     * @param Content $content
     * @return Content|RedirectResponse
     */
    public function edit($id, Content $content)
    {
        if (!$id) {
            admin_error('参数错误！', 'warning');
        }
        $where['id'] = $id;
        //编辑wiki
        $baseInfo = TodayNiceGoodsModel::first($where);
        $baseInfo = TodayNIceGoodsService::formatList([$baseInfo])[0] ?? [];
        if (!$baseInfo) {
            $error = new MessageBag([
                'title' => '信息不存在或已删除',
            ]);

            return back()->with(compact('error'));
        }
        $baseForm = new Form($baseInfo);
        $baseForm->disableReset();
        $baseForm->display('brand_name', '品牌名称');
        $baseForm->display('brand_id', '品牌id');
        // 显示记录id
        $this->_getForm($baseForm);
        if ($baseInfo['status'] == TodayNiceGoodsModel::STATUS_ACTING) {
            $baseForm->date('start_at', '开始时间')->disable();
        } else {
            $baseForm->date('start_at', '开始时间')->default(date("Y-m-d 00:00:00"))->required();
        }
        $baseForm->hidden('id');

        $baseForm->confirm('确定更新吗？');
        $baseForm->action('/admin/TodayNiceGoods/save');

        return $content
            ->header('修改')
            ->description(' ')
            ->breadcrumb(
                ['text' => '找好物列表', 'url' => '/TodayNiceGoods/index'],
                ['text' => '找好物修改']
            )
            ->row($baseForm);

    }

    /**
     * form
     * @param $baseForm
     */
    private function _getForm($baseForm)
    {
//        $baseForm->text('brand_id', '品牌id');
//        $baseForm->text('brand_name', '品牌名称');
        $baseForm->text('basic_id', 'wiki_id')->required();
//        $baseForm->text('wiki_id', '商品_id')->required();
        $options = TodayNiceGoodsModel::TYPE_ARR;
        $baseForm->select('type', '活动类型')->options($options)->default(TodayNiceGoodsModel::TYPE_NORMAL);
        $baseForm->imgUpload('img', '商品图', false, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BIZ,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
        ])->help("仅支持一张图片上传，小于500k");

        $baseForm->imgUpload('back_img', '背景图片', false, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BIZ,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
        ])->help("仅支持一张图片上传，小于2M");

        $baseForm->imgUpload('back_show_img', '展台图片', false, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BIZ,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
        ])->help("仅支持一张图片上传，小于2M");

        $baseForm->text('tags', '亮点')->help("多个用英文逗号,隔开最多3个。单个亮点字数限制7个");
        $baseForm->text('title', '(title)主标题')->required();
        $baseForm->text('sec_title', '(sec_title)副标题')->required();
    }

    /**
     * 保存
     * @param Request $request
     * @return Application|RedirectResponse|Redirector
     */
    public function save(Request $request)
    {
        try {
            $params = $request->all();
//            if ($params['start_at'] < date("Y-m-d 00:00:00")) {
//                throw new \Exception("开始时间不能小于当前时间!");
//            }
            $rules = $this->_getRules();
            //更新
            if (isset($params['id']) && $params['id']) {
                $info = TodayNiceGoodsModel::first(['id' => $params['id']], ['id', 'start_at', 'end_at']);
                if (!$info) {
                    throw new \Exception('该活动不存在！');
                }
                $start_at = isset($params["start_at"]) ? date('Y-m-d 00:00:00', strtotime($params["start_at"])) : $info['start_at'];
            } else {
                $start_at = $params["start_at"] ? date('Y-m-d 00:00:00', strtotime($params["start_at"])) : date("Y-m-d 00:00:00");
            }
            //校验参数
            $res_msg = Common::validatorRule($rules, $params);
            if ($res_msg !== true) {
                throw new \Exception($res_msg);
            }
            $tags = $params["tags"] ? str_replace("，", ",", trim($params["tags"])) : '';
            if ($tags) {
                $tags = $tags ? explode(',', $tags) : [];
                foreach ($tags as $tag) {
                    if (mb_strlen($tag) > 7) {
                        throw new \Exception('亮点字符不能超过7个');
                    }
                }
                //亮点数量
                $count = count($tags);
                if ($count > 3) {
                    throw new \Exception('亮点不能超过三个');
                }
            }
            $data = [
                "basic_id" => $params["basic_id"] ?? 0,
                "type" => $params["type"],
                "img" => $params["img"] ?? '',
                "back_img" => $params["back_img"] ?? '',
                "back_show_img" => $params["back_show_img"] ?? '',
                "title" => $params["title"] ?? '',
                "sec_title" => $params["sec_title"] ?? '',
                "tags" => $tags ? implode(",", $tags) : '',
                "start_at" => $start_at,
                "admin_id" => Admin::user()->id,
                "end_at" => date('Y-m-d 23:59:59', strtotime($start_at)),
                "month" => date('Y-m', strtotime($start_at)) ?: date('Y-m', time()),
                "updated_at" => date('Y-m-d H:i:s'),
            ];
            $wiki_id = Wiki::getInfoByBasicId($data['basic_id'], 'id');

            if (!$wiki_id) {
                throw new \Exception('商品不存在');
            }
            $data['wiki_id'] = $wiki_id;
            $brandInfo = WikiBasic::getBrandInfoByBasicId($params["basic_id"]);
            $data["brand_id"] = $brandInfo["id"] ?? 0;
            $data["brand_name"] = $brandInfo["brand_name"] ?? '';

            $success = new MessageBag([
                'title' => '成功',
            ]);
            //更新
            if (isset($params['id']) && $params['id']) {
                $isset = TodayNiceGoodsModel::first(['start_at' => $start_at, 'id[!]' => $params['id'], 'status[!]' => TodayNiceGoodsModel::STATUS_DELETE], 'id');
                if ($isset) {
                    throw new \Exception('当前日期已经存在活动！');
                }
                $this->updateData($params['id'], $data);
                return redirect('/admin/TodayNiceGoods/index/' . $params['id'] . '/edit')->with(compact('success'))->withInput();
            } else {

                $isset = TodayNiceGoodsModel::first(['start_at' => $start_at, 'status[!]' => TodayNiceGoodsModel::STATUS_DELETE], 'id');
                if ($isset) {
                    throw new \Exception('当前日期已经存在活动！');
                }
                $this->insertData($data);
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);
            return back()->with(compact('error'))->withInput();
        }

        return redirect('/admin/TodayNiceGoods/index')->with(compact('success'));
    }

    /**
     * 更新
     * @param $id
     * @param $data
     * @return void
     */
    private function updateData($id, $data): void
    {
        $where['id'] = $id;
        TodayNiceGoodsModel::update($data, $where);
    }

    /**
     * 新增
     * @param $data
     * @return void
     */
    private function insertData($data): void
    {
        $data['created_at'] = date("Y-m-d H:i:s");
        $data['admin_id'] = Admin::user()->id;
        TodayNiceGoodsModel::insert($data);
    }

    /**
     * 表单参数校验
     * @return string[]
     */
    private function _getRules(): array
    {
        $rules = [
            'id' => 'integer',
            "brand_id" => 'integer',
            "basic_id" => 'required|integer',
            "type" => 'required|integer',
            "img" => 'required',
            "back_img" => 'required',
            "back_show_img" => 'required',
//            "tags" => 'required',
            "title" => 'required',
            "sec_title" => 'required',
            "start_at" => 'date',
        ];
        return $rules;
    }

    /**
     * 新增
     * @param Request $request
     * @param Content $content
     * @param Form $form
     * @return Content
     */
    public function create(Request $request, Content $content, Form $form): Content
    {
        $form->disableReset();
        $this->_getForm($form);
        $form->date('start_at', '开始时间')->required();
        $form->confirm('确定新增吗？');
        $form->action('/admin/TodayNiceGoods/save');

        return $content
            ->header('新增')
            ->description(' ')
            ->breadcrumb(
                ['text' => '活动列表', 'url' => '/TodayNiceGoods/index'],
                ['text' => '新增']
            )
            ->row($form);
    }


    /**
     * 活动中排序
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function sortLists(Request $request, Content $content): Content
    {
        $params = $request->all();
        $where['status'] = TodayNiceGoodsModel::STATUS_NORMAL;
        $count = TodayNiceGoodsModel::count($where);
        $where['start_at[<=]'] = date('Y-m-d H:i:s');
        $where['end_at'] = date('Y-m-d 23:59:59');

        if ($params['type']) {
            $where['type'] = $params['type'];
        }
        $where['ORDER'] = [
            'sort' => "DESC",
            'start_at' => 'DESC',
        ];
        $where['LIMIT'] = TodayNIceGoodsService::ACT_NUM;
        $list = TodayNiceGoodsModel::all($where);
        $list = TodayNiceGoodsService::formatList($list);
        $gridModel = new GridDataModel($list, $count);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disablePagination();
                $grid->disableCreateButton();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'id')->sort()->sortable();
                $grid->column('brand_name', '品牌名称');
                $grid->column('basic_id', 'WIKI_ID');
                $grid->column('img_url', '商品图片')->image();
                $grid->column('title', '标题');
                $grid->column('type', '活动类型')->using(
                    TodayNiceGoodsModel::TYPE_ARR
                    , '未知')->label([
                    1 => 'default',
                    2 => 'primary',
                ]);
                $grid->column('start_at', '上线时间')->sortable();
                $grid->column('status', '状态')->using(
                    TodayNiceGoodsModel::STATUS_ARR
                    , '未知')->label([
                    12 => 'success',
                    9 => 'info',
                    11 => 'warning',
                    13 => 'danger',
                ]);
                $grid->disableActions();
            }
        );
        $tab = new Tab();
        $tab->addLink('找好物列表', url('/admin/TodayNiceGoods/index'), false);
        $tab->add('活动中排序', $grid->render(), true);
        $tab->addLink('白名单', url('/admin/TodayNiceGoods/whiteusers'), false);
        $content->row($tab);

        return $content
            ->header('活动中排序')
            ->description(' ')
            ->breadcrumb(['text' => '活动中排序', 'url' => '/TodayNiceGoods/sortlists']);
    }

    /**
     * 拖动排序
     * @param Request $request
     */
    public function sort(Request $request): void
    {
        $params = $request->all();
        $sorts = $params['sort'];
        $desc_sorts = array_reverse($sorts);
        $arr = array_flip($sorts);
        $sort_arr = [];
        //将排序更改为倒叙
        foreach ($desc_sorts as $k => $v) {
            $sort_arr[$arr[$k]] = $v;
        }
        if ($sort_arr && is_array($sort_arr)) {
            foreach ($sort_arr as $id => $sort) {
                $data['sort'] = $sort;
                $data['updated_at'] = date('Y-m-d H:i:s');
                $data['admin_id'] = Admin::user()->id;
                TodayNiceGoodsModel::update($data, ['id' => $id]);
            }
        }
    }


    /**
     * 编辑
     * @param Content $content
     * @return Content
     */
    public function whiteUsers(Content $content): Content
    {
        $baseInfo = BlindBox::get(BlindBox::TODAY_NICE_GOODS_WHITE_USERS);
        $baseForm = new Form();
        $baseForm->disableReset();
        $baseForm->text('white_users', '白名单')->default($baseInfo)->help("多个用英文逗号,隔开");

        $baseForm->confirm('确定更新吗？');
        $baseForm->action('/admin/TodayNiceGoods/whitesave');

        return $content
            ->header('修改')
            ->description(' ')
            ->breadcrumb(
                ['text' => '找好物列表', 'url' => '/TodayNiceGoods/index'],
                ['text' => '找好物修改']
            )
            ->row($baseForm);

    }

    /**
     * 保存白名单
     * @param Request $request
     * @return Application|RedirectResponse|Redirector
     */
    public function whiteSave(Request $request)
    {
        $params = $request->all();
        $white_users = $params['white_users'] ? str_replace('，', ',', $params['white_users']) : '';
        $res = BlindBox::set(BlindBox::TODAY_NICE_GOODS_WHITE_USERS, $white_users);

        if (!$res) {
            $error = new MessageBag([
                'title' => '保存失败，请重试！',
            ]);
            return back()->with(compact('error'))->withInput();
        }

        $success = new MessageBag([
            'title' => '成功',
        ]);
        return redirect('/admin/TodayNiceGoods/whiteusers')->with(compact('success'));

    }

}